package legumes.client.ui.admin.stall;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.GenerateOrdersReportCallback;
import legumes.client.services.callbacks.GetOrdersCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.widgets.utils.Formatters;
import legumes.shared.domain.Order;
import legumes.shared.domain.OrderPart;

import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

public class AdminOrdersPanel extends VLayout {
	private ListGrid ordersGrid;
	private long sellSessionId;
	
	public AdminOrdersPanel() {
		super();
		setWidth100();
		setHeight100();
		
		build();
	}
	
	private ToolStrip createToolBar(){
		ToolStrip toolStrip = new ToolStrip();
		toolStrip.setWidth100();
		toolStrip.setHeight(21);
		
		ToolStripButton excelExportButton = new ToolStripButton();  
		excelExportButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				generateExcel();
			}
		});
		excelExportButton.setIcon(PNResources.INSTANCE.excelIcon().getURL());  
		excelExportButton.setTitle("Save as excel file...");  
        toolStrip.addButton(excelExportButton);
        
        return toolStrip;
	}
	
	protected void generateExcel() {
		RPCCallSequencer callSequencer = new RPCCallSequencer(
				"Génération en cours...");

		final GenerateOrdersReportCallback genCallback = 
			new GenerateOrdersReportCallback(
				sellSessionId);
		callSequencer.addCall(genCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				com.google.gwt.user.client.Window.open(genCallback.getVpathReport(), "report", null);
			}
		});

		callSequencer.callSequence();
	}
	
	public void refreshData(){
		initData(this.sellSessionId);
	}
	
	public void initData(long sellSessionId_){
		sellSessionId = sellSessionId_;
		RPCCallSequencer callSequencer = new RPCCallSequencer("Chargement en cours...");

		final GetOrdersCallback getOrdersCallback = new GetOrdersCallback(sellSessionId);
		callSequencer.addCall(getOrdersCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				List<ListGridRecord> records = new ArrayList<ListGridRecord>();
				Collection<Order> orders = getOrdersCallback.getOrders();
				if(orders != null){
					for (Order order : orders) {
						for (OrderPart op : order.getOrderParts()) {
							ListGridRecord lgr = new ListGridRecord();
							lgr.setAttribute("date", new Date(order.getDate()) );
							lgr.setAttribute("orderNum", op.getId() );
							lgr.setAttribute("customerName", order.getCustomerName() );
							lgr.setAttribute("basket", op.getOrderPartMenuItem().getMenuCountAsEnum().getDisplayName() );
							lgr.setAttribute("without", op.getWithoutAsString() );
							lgr.setAttribute("with", op.getWithAsString() );
							lgr.setAttribute("price", op.computePrice().getValue() );
							
							records.add(lgr);
						}
					}
				}
				if( records.size()>0){
					ordersGrid.setRecords(records.toArray(new ListGridRecord[0]));
				}
			}
		});
		
		callSequencer.callSequence();
	}
	
	private void build(){
        ordersGrid = new ListGrid();
        ordersGrid.setShowRollOverCanvas(true);  
        ordersGrid.setCanEdit(true);
        ordersGrid.setWidth100();
        ordersGrid.setHeight("50%");  
        ordersGrid.setShowAllRecords(true);  
        ordersGrid.setCellHeight(22);  
        
        ordersGrid.setSelectionType(SelectionStyle.SIMPLE);  
        ordersGrid.setSelectionAppearance(SelectionAppearance.ROW_STYLE);
        ordersGrid.setEditByCell(false);
        ordersGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX); 
        
        ListGridField orderDateField = new ListGridField("date", "Date", 100);
        orderDateField.setCanEdit(false);
        orderDateField.setType(ListGridFieldType.DATE);
        orderDateField.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATETIME);
        
        ListGridField orderNumField = new ListGridField("orderNum", "Num", 20);
        orderNumField.setCanEdit(false);
        orderNumField.setType(ListGridFieldType.INTEGER);
        
        ListGridField customerNameField = new ListGridField("customerName", "Customer", 80);
        customerNameField.setType(ListGridFieldType.FLOAT);
        customerNameField.setCanEdit(false);
        
        final ListGridField basketField = new ListGridField("basket", "Panier", 50);
        basketField.setType(ListGridFieldType.FLOAT);
        basketField.setCanEdit(false);
        
        final ListGridField baskerWithoutField = new ListGridField("without", "Sans", 100);
        baskerWithoutField.setCanEdit(false);
        
        final ListGridField baskerWithField = new ListGridField("with", "Avec", 100);
        baskerWithField.setCanEdit(false);
        
        final ListGridField priceField = new ListGridField("price", "Prix", 50);
        priceField.setType(ListGridFieldType.FLOAT);
        priceField.setCanEdit(false);
        priceField.setCellFormatter(new CellFormatter(){

            @Override
            public String format(Object value_, ListGridRecord record_, int rowNum_, int colNum_) {
                return value_ == null ? null : Formatters.formatPrice(value_, true);
            }
            
        });
        
        ordersGrid.setFields(orderDateField, orderNumField, customerNameField, basketField, baskerWithoutField, baskerWithField, priceField);  
        
        setMembers(createToolBar(), ordersGrid);
	}

		
}
